﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kovan.Library.Json;
using System.Text.RegularExpressions;
using System.Web;

namespace Kovan.Library.Utils
{
    public class UrlHelper
    {
        private bool Match(string url, string[] keys)
        {
            foreach (var key in keys)
            {
                if (Regex.IsMatch(url, key))
                    return true;
            }
            return false;
        }

       

        private static Regex DomainRegex = RegexUtility.CreateRegex(@"(?<Domain>([^:\./ ]+\.(com\.cn|net\.cn|org\.cn|gov\.cn|com|cn|mobi|tel|asia|net|org|name|me|tv|cc|hk|biz|info|in|[a-z]{2,})|\d+\.\d+.\d+.\d+))($|\s|/)");

        public static string AbsoluteUrl(string baseUri, string childUri)
        {
            return new Uri(new Uri(baseUri), childUri).AbsoluteUri;
        }

        public static string GetDomainName(string url)
        {
            var matchs = DomainRegex.Matches(url);
            if (matchs.Count == 0)
            {
                return string.Empty;
            }
            return matchs[0].Groups["Domain"].Value;

        }

        /// <summary>
        /// 对象转为URL参数
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToUrlParameter(object obj)
        {
            if (obj == null) return string.Empty;
            var properties = obj.GetType().GetProperties();
            List<object> list = new List<object>();
            StringBuilder psb = new StringBuilder();
            string v = string.Empty;
            foreach (var p in properties)
            {
                var value = p.GetValue(obj, null);
                v = value != null ? value.ToString() : string.Empty;
                var type = p.PropertyType.FullName;
                var index = type.IndexOf("[");
                // 当值为复杂类型时(判断依据：v返回的值跟type值类似，都是表示类路径的)
                if (value != null && index > 0 && v.EndsWith("]") && type.EndsWith("]") &&
                    v.Length > index && v.Substring(0, index).Equals(type.Substring(0, index)))
                {
                    v = value.ToJson();
                    // 如果是数组，去掉数组的前后中括号
                    if (v.StartsWith("[") && v.EndsWith("]"))
                    {
                        v = v.Substring(1);
                        v = v.Substring(0, v.Length - 1);
                    }
                    // 如果里面包含的是字符串，去掉括号(字符串里面包含逗号时会引起歧义)
                    if (v.StartsWith("\"") && v.EndsWith("\""))
                    {
                        v = v.Trim('"').Replace("\",\"", ",");
                    }
                }

                // UrlEncode
                foreach (Attribute attr in p.GetCustomAttributes(true))
                {
                    if (attr is Attributes.FieldEncodingAttribute)
                    {
                        Attributes.FieldEncodingAttribute a = attr as Attributes.FieldEncodingAttribute;
                        if (a.Encod.ToLower() == "urlencode")
                        {
                            v = HttpUtility.UrlEncode(v);
                        }
                        break;
                    }
                }
                v = v.Replace("&", "%26");
                psb.AppendFormat("{0}={1}&", new object[] { p.Name, v });
            }
            return psb.ToString().TrimEnd(new char[] { '&' });
        }
    }
}
